<template>
  <div class="add-role">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>添加角色</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="activeStep">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>

      <!-- 角色信息 -->
      <div v-show="activeStep === 1" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form ref="form" label-width="100px" :model="form" :rules="rules">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="form.name" style="width: 500px;" />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="form.description" type="textarea" :rows="5" style="width: 500px;" />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 权限配置 -->
      <div v-show="activeStep === 2" class="form-container">
        <div class="title">权限配置</div>
        <div class="form">
          <template>
            <div class="tree-wrapper">
              <div v-for="item in treeList" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  ref="tree"
                  :data="item.children"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  highlight-current
                  :props="{ label: 'title', children: 'children' }"
                />
              </div>
            </div>
          </template>
        </div>
      </div>

      <!-- 检查并完成 -->
      <div v-show="activeStep === 3" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ form.name }}</div>
            <div class="form-item">角色描述：{{ form.description }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div v-for="item in diabledTree" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  ref="diabledTree"
                  :data="item.children"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :highlight-current="false"
                  :props="{ label: 'title' }"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-show="activeStep !== 1" @click="prevStep">上一步</el-button>
        <el-button v-show="activeStep !== 3" type="primary" @click="nextStep">下一步</el-button>
        <el-button v-show="activeStep === 3" type="primary" @click="addRole">确认添加</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getRoleTreeAPI, submitRoleAPI, getRoleDetailAPI, updateRoleAPI } from '@/api/role'

export default {
  data() {
    return {
      activeStep: 1, // 控制显示哪个步骤
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      treeList: [], // 树形列表
      checkedList: [], // 选中的节点
      diabledTree: [], // 禁用的树形列表,
      checkedKeys: [], // 选中的节点id
      roleId: '' // 角色id
    }
  },
  created() {
    this.getTreeList()
    // this.getRoleId()
    if (this.$route.params.id) {
      this.getRoleInfo()
    }
  },
  methods: {
    // 发送请求回显数据
    async getRoleInfo() {
      console.log(this.$route.params.id)
      const { data: { roleName, remark, perms }} = await getRoleDetailAPI(this.$route.params.id)
      this.form.name = roleName
      this.form.description = remark
      this.checkedKeys = perms
      // console.log('perms', perms)
      // console.log('this.$refs.diabledTree', this.$refs.diabledTree)

      this.$refs.tree.forEach((item, index) => {
        // console.log('perms[index]', perms[index])
        item.setCheckedKeys(perms[index])
      })
    },
    // 确认添加
    async addRole() {
      if (this.$route.params.id) {
        // 编辑
        console.log('data', this.form)

        await updateRoleAPI({ roleId: this.$route.params.id, roleName: this.form.name, remark: this.form.description, perms: this.checkedKeys })
        this.$message.success('编辑角色成功')
        // 跳转
        this.$router.push('/sys/role')
      } else {
        // 新增
        // 获取选中节点的id
        this.$refs.diabledTree.forEach(item => {
          this.checkedKeys.push(item.getCheckedKeys())
        })
        // console.log('checkedKeys', this.checkedKeys)
        // 发送请求
        await submitRoleAPI({
          roleName: this.form.name,
          remark: this.form.description,
          perms: this.checkedKeys
        })
        // 提示用户
        this.$message.success('添加角色成功')
        // 跳转
        this.$router.push('/sys/role')
      }
    },
    // 禁用树形组件
    disabledTree(data) {
      data.forEach(item => {
        // item 是树形结构中的节点
        // 设置节点禁用
        item.disabled = true
        if (item.children) {
          // 递归调用 ,实现树形节点禁用
          this.disabledTree(item.children)
        }
      })
    },
    // 下一步
    async nextStep() {
      if (this.activeStep !== 3) {
        if (this.activeStep === 1) {
          // 校验整个表单
          await this.$refs.form.validate()
          this.activeStep++
        } else if (this.activeStep === 2) {
          // 判断该页面是否选择了权限
          //   console.log(this.$refs.tree)
          // this.$refs.tree 收集了 多个 el-tree 组件,是一个数组 里面每一项都是 el-tree 组件
          this.$refs.tree.forEach(item => {
            // item.getCheckedNodes() 获取当前组件选中的节点,包含子节点
            // console.log(item.getCheckedNodes())

            // this.checkedList 存储的数据是 数组包数组
            this.checkedList.push(item.getCheckedNodes())
          })
          // flat() 该方法用于将多维数组转化为一维数组
          if (this.checkedList.flat().length === 0) {
            this.$message.error('请至少选择一个权限点')
          } else {
            this.activeStep++

            // 回填数据
            /*
            [问题]:数据无法回显
            [原因]:获取选中的数据时,使用了不同方法,导致数据格式不一致
            getCheckedNodes() 获取选中的节点,包含子节点,返回的是完整的节点数据
            getCheckedKeys() 获取选中的节点,不包含子节点,返回的是节点的id
            [解决]:
            使用 getCheckedKeys() 方法获取选中的节点,包含子节点,返回的是节点的id
            使用 setCheckedKeys() 方法设置选中的节点,包含子节点,返回的是节点的id
            ==================================================================
            使用 getCheckedNodes() 方法获取选中的节点,包含子节点,返回的是完整的节点数据
            使用 setCheckedNodes() 方法设置选中的节点,包含子节点,传入的是完整的节点对象数组
            */
            this.$refs.diabledTree.forEach((item, index) => {
              item.setCheckedNodes(this.checkedList[index])
            })
            // 禁用树形结构
            this.disabledTree(this.diabledTree)
          }
        }
      }
    },
    // 上一步
    prevStep() {
      if (this.activeStep !== 1) {
        this.activeStep--
      }
    },

    // 获取树形列表
    async getTreeList() {
      const { data } = await getRoleTreeAPI()
      this.treeList = data
      this.diabledTree = JSON.parse(JSON.stringify(data))
      console.log('this.treeList', this.treeList)
    }
  }

}
</script>
<style scoped lang="scss">
.add-role {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
        display: flex;
        justify-content: space-between;
        padding: 0 20px;
        height: 64px;
        line-height: 64px;
        font-size: 16px;
        font-weight: bold;
        background-color: #fff;

        .left {
            span {
                margin-right: 4px;
            }

            .arrow {
                cursor: pointer;
            }
        }

        .right {
            text-align: right;
        }
    }

    .add-main {
        position: fixed;
        top: 64px;
        bottom: 88px;
        width: 100%;
        overflow-y: auto;
        background: #f4f6f8;
        padding: 20px 230px;
        display: flex;

        .step-container {
            height: 400px;
            width: 200px;
        }

        .form-container {
            flex: 1;
            background-color: #fff;
            overflow-y: auto;

            .title {
                height: 60px;
                line-height: 60px;
                padding-left: 20px;
            }

            .form {
                margin-bottom: 20px;
                padding: 20px 65px 24px;

                .el-form {
                    display: flex;
                    flex-wrap: wrap;
                }

                .info {
                    font-size: 14px;
                    color: #666;

                    .form-item {
                        margin-bottom: 20px;
                    }
                }
            }

            .form-box {
                width: 600px;
                display: flex;
                flex-direction: column;
            }
        }
    }

    .add-footer {
        position: fixed;
        bottom: 0;
        width: 100%;
        padding: 24px 50px;
        color: #000000d9;
        font-size: 14px;
        background: #fff;
        text-align: center;
        z-index: 10001;
    }

    .tree-wrapper {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;

        .tree-item {
            flex: 1;
            padding: 0px 4px;
            text-align: center;

            .tree-title {
                background: #f5f7fa;
                text-align: center;
                padding: 10px 0;
                margin-bottom: 12px;
            }
        }
    }
}
</style>
